import axios from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store'
import { checkTimeout } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      if (checkTimeout()) {
        store.dispatch('user/logout')
        return Promise.reject(new Error('登录失效，请重新登录'))
      }
      config.headers.Authorization = `Bearer ${store.getters.token}`
      config.headers.token = `${store.getters.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use((response) => {
  const { code, message, data } = response.data || {}

  if (code === 200) {
    return data
  } else if (code === 401) {
    ElMessage.error(message)
    store.dispatch('user/logout')
  } else {
    ElMessage.error(message)
    return Promise.reject(new Error(message))
  }
}, (error) => {
  if (
    error.response &&
    error.response.data &&
    error.response.data.code === 401
  ) {
    // token超时
    store.dispatch('user/logout')
  }
  ElMessage.error(error.message)
  return Promise.reject(error)
})

export default service
